<template>
  <el-dialog
    :title="title"
    v-model="model"
    width="800px"
    :before-close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="商品标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入商品标题" />
      </el-form-item>
      <el-form-item label="副标题" prop="subtitle">
        <el-input v-model="form.subtitle" placeholder="请输入副标题" />
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item label="分类" prop="categoryId">
            <el-select v-model="form.categoryId" placeholder="请选择分类">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-input v-model="form.unit" placeholder="请输入单位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="form.sort" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">下架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="封面图" prop="coverImage">
        <UploadImage
          :limit="1"
          :fileList="coverImageList"
          @fileChange="handleCoverImageChange"
        />
      </el-form-item>
      <el-form-item label="轮播图" prop="carouselImage">
        <UploadImage
          :limit="5"
          :fileList="carouselImageList"
          @fileChange="handleCarouselImageChange"
        />
      </el-form-item>
      <el-form-item label="商品详情" prop="detail">
        <editor v-model="form.detail" :min-height="180" />
      </el-form-item>

      <el-form-item label="SKU" prop="skuList">
        <el-form
          class="mb-2"
          :model="item"
          v-for="(item, index) in form.skuList"
          :rules="skuRules"
          ref="skuFormRef"
          size="small"
          :key="index"
        >
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="规格名称" prop="specValueNames">
                <el-input
                  v-model="item.specValueNames"
                  placeholder="请输入规格"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="价格" prop="salePrice">
                <el-input
                  v-model="item.salePrice"
                  type="number"
                  placeholder="请输入价格"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="库存" prop="stock">
                <el-input
                  v-model="item.stock"
                  type="number"
                  placeholder="请输入库存"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-button type="primary" size="small" @click="addSkuHandle"
          >添加规格</el-button
        >
      </el-form-item>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import UploadImage from "@/components/upload/image";
import {
  getMallCategoryPage,
  saveMallProduct,
  updateMallProduct,
} from "@/api/operateManage";
// 导入相关API
// import { addProduct, updateProduct } from '@/api/product';

const props = defineProps({
  title: {
    type: String,
    default: "添加商品",
  },
  row: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["submit"]);
const model = defineModel({
  default: false,
});
const isEdit = computed(() => !!props.row.id);

const formRef = ref(null);
const skuFormRef = ref(null);
const form = ref({
  title: "",
  subtitle: "",
  categoryId: "",
  coverImage: "",
  carouselImage: "",
  detail: "",
  unit: "",
  sort: 1,
  status: 1,
  skuList: [],
});
const skuField = {
  specValueNames: "",
  salePrice: "",
  stock: "",
};

const coverImageList = ref([]);
const carouselImageList = ref([]);

const rules = reactive({
  title: [{ required: true, message: "请输入商品标题", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择分类", trigger: "change" }],
  unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
  coverImage: [{ required: true, message: "请上传封面图", trigger: "change" }],
  carouselImage: [
    { required: true, message: "请上传轮播图", trigger: "change" },
  ],
  detail: [{ required: true, message: "请输入商品详情", trigger: "blur" }],
  skuList: [{ required: true, message: "请添加规格", trigger: "blur" }],
  // 其他验证规则...
});
const skuRules = reactive({
  specValueNames: [
    { required: true, message: "请输入规格名称", trigger: "blur" },
  ],
  salePrice: [{ required: true, message: "请输入价格", trigger: "blur" }],
  stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
});
const categoryList = ref([]);

//验证现有规格， 并添加规格
const addSkuHandle = () => {
  if (skuFormRef.value) {
    skuFormRef.value.forEach((formRef) => {
      formRef.validate((valid) => {
        if (valid) {
          form.value.skuList.push({ ...skuField });
        }
      });
    });
  } else {
    form.value.skuList.push({ ...skuField });
  }
};

// 获取分类
const getMallCategoryList = () => {
  getMallCategoryPage({
    pageNo: 1,
    pageSize: 9999,
  }).then(({ data }) => {
    categoryList.value = data.records;
  });
};

const handleClose = () => {
  model.value = false;
};

const handleCoverImageChange = (files) => {
  coverImageList.value = files;
  form.value.coverImage = files.length > 0 ? files[0].url : "";
};

const handleCarouselImageChange = (files) => {
  carouselImageList.value = files;
  form.value.carouselImage = files.map((file) => file.url).join(",");
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (skuFormRef.value) {
        const skuValid = [];
        skuFormRef.value.forEach((formRef) => {
          formRef.validate((valid) => {
            skuValid.push(valid);
          });
        });
        setTimeout(() => {
          if (skuValid.length && skuValid.every((item) => item)) {
            // 处理表单提交逻辑
            const api = isEdit.value ? updateMallProduct : saveMallProduct;
            const params = {
              ...form.value,
            };
            api(params)
              .then(({ data }) => {
                if (data) {
                  ElMessage.success(isEdit.value ? "编辑成功" : "添加成功");
                  handleClose();
                  emit("submit");
                }
              })
              .catch((error) => {
                ElMessage.error("操作失败：" + error.message);
              });
          }
        }, 0);
      }
    }
  });
};

onMounted(() => {
  getMallCategoryList();
  console.log("[ isEdit ] >", isEdit.value);
  if (isEdit.value) {
    coverImageList.value.push({
      fileName: props.row.coverImage,
      url: props.row.coverImage,
      uid: Date.now() + Math.random(),
    });
    props.row.carouselImage.split(",").forEach((item) => {
      carouselImageList.value.push({
        fileName: item,
        url: item,
        uid: Date.now() + Math.random(),
      });
    });
    form.value = { ...props.row, skuList: props.row.mallProductSkuList || [] };
  }
});
</script>

<style scoped>
.el-input,
.el-input-number,
.el-select {
  width: 100%;
}
</style>
